<template>
  <div>
    <!--添加按钮-->
    <el-button style="margin-top: 10px" size="mini" type="success" @click="addDialogVisible = !addDialogVisible">添加
    </el-button>
    <!--商品信息列表-->
    <el-table :data="goodsTableData"
              style="width: 100%" height="70vh" header-align="center" @expand-change="showGoodsInfoById"
              :row-key="getRowKeys" :expand-row-keys="expands">
      <el-table-column type="expand">
        <template slot-scope="scope">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-date-picker
                v-model="queryGoodsInfoWithMonth"
                type="monthrange"
                range-separator="至"
                start-placeholder="开始月份"
                end-placeholder="结束月份"
                format="yyyy 年 MM 月"
                value-format="yyyy-MM-dd">
            </el-date-picker>
            <span><el-button type="primary" icon="el-icon-search" style="margin-left: 20px"
                             @click="queryGoodsInfoByMonth()">搜索</el-button></span>
            <el-timeline :reverse="true">
              <el-timeline-item
                  v-if="goodsInfoTableData"
                  v-for="(item, index) in goodsInfoTableData"
                  :key="index"
                  :timestamp="item.update_time">
                {{ item.msg_user + ' 于 ' + item.update_time + ' 对 ' + item.goods_name + ' 的库存 ' }}{{ (item.result_number >= 0) ? '增加了' + item.result_number + '个' : '减少了' + Math.abs(item.result_number) + '个' }}
              </el-timeline-item>
              <p v-else>暂无数据~</p>
            </el-timeline>
            <p style="margin-top: 10px" v-if="queryGoodsInfoResult !=''">本月进货量 {{parseInt(queryGoodsInfoResult)>=0? '增加了'+queryGoodsInfoResult+'个':'减少了'+Math.abs(queryGoodsInfoResult)+'个'}}</p>
            <p style="margin-top: 20px" v-else></p>
          </el-form>
        </template>
      </el-table-column>


      <el-table-column label="ID" width="150" prop="id" align="center"/>
      <el-table-column label="商品名称" width="200" prop="name" align="center"/>
      <el-table-column label="商品价格" width="200" prop="price" align="center"/>
      <el-table-column label="库存数量" width="150" prop="number" align="center"/>

      <!--使用scpoe 直接获取当前列，再.row获取当前行数据，使用number进行v-if判断-->
      <el-table-column label="库存状态" width="150" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.number <=10" style="color: red">缺货，请立马补充</span>
          <span v-else>正常</span>
        </template>
      </el-table-column>

      <el-table-column label="分类名称" width="200" prop="cat_name" align="center"/>
      <el-table-column>
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" @change="" size="medium" style="width: auto" placeholder="输入商品名称关键字搜索"
                    suffix-icon="el-icon-search"/>
        </template>
        <template slot-scope="scope">
          <!--编辑按钮-->
          <el-button class="margin-left" type="primary"
                     @click="handleEdit(scope.row)">编辑
          </el-button>
          <el-popconfirm
              confirm-button-text='给我删！'
              cancel-button-text='不删了'
              icon="el-icon-info"
              icon-color="red"
              title="确定删除该商品吗？"
              @confirm="deleteGoodsById(scope.row)">
            <!--删除按钮-->
            <el-button class="margin-left" type="danger" slot="reference">删除</el-button>
          </el-popconfirm>
          <el-button class="margin-left" type="primary"
                     @click="handleNumEdit(scope.row)">进货
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-row type="flex" justify="center">
      <el-col :span="12">
        <el-pagination
            style="margin: 15px 0px"
            background
            layout="prev, pager, next, jumper, total, sizes"
            :page-size="size"
            :current-page="now"
            :page-sizes="[2,4,6,8,10,12]"
            @current-change="findPage"
            @size-change="findSize"
            :total="total">
        </el-pagination>
      </el-col>
    </el-row>
    <!--添加表单-->
    <el-dialog title="添加商品" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed()">
      <el-form ref="addFormRef" :model="addForm" label-suffix=":" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="addForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品数量">
          <el-input type="input" v-model="addForm.number"></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="addForm.cat_id" placeholder="请选择">
            <el-option
                v-for="item in categoryData"
                :key="item.cat_id"
                :label="item.cat_name"
                :value="item.cat_id">
              <!--  被选中的value  会反馈回给 v-model里，我们添加的数据只需要加id-->
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item>
          <el-button type="primary" @click="addGoods()">添加商品</el-button>
          <el-button @click="clearAddInfo">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!--修改表单-->
    <el-dialog title="修改商品" :visible.sync="updateDialogVisible" width="50%" @close="updateDialogClosed()">
      <el-form ref="editFormRef" :model="editForm" label-suffix=":" label-width="80px">
        <el-form-item label="修改名称">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="修改价格">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="editForm.cat_id" placeholder="请选择">
            <el-option
                v-for="item in categoryData"
                :key="item.cat_id"
                :label="item.cat_name"
                :value="item.cat_id">
              <!--  被选中的value  会反馈回给 v-model里，我们添加的数据只需要加id-->
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateGoods()">修改商品</el-button>
          <el-button @click="clearEditInfo">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>


    <el-dialog title="进货" :visible.sync="updateGoodsNumDialogVisible" width="50%" @close="updateGoodsNumDialogClosed()">
      <el-form :model="editNumForm" label-suffix=":" label-width="80px">
        <el-form-item label="修改数量">
          <el-input v-model="editNumForm.next_number"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateGoodsNum()">修改数量</el-button>
          <el-button @click="clearEditGoodsNumInfo">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      test: '',
      goodsTableData: [], //商品表单数据
      categoryData: [], //商品分类数据 渲染下拉框用
      goodsInfoTableData: [], //默认只能展开一行 所以一般只有一个对象
      queryGoodsInfoWithMonth: [], //  查找商品信息  这里存放的是要查找几月到几月的字符串
      queryGoodsInfoResult:'',  // 放当前月总进货数量
      search: '',  //
      addDialogVisible: false,
      updateDialogVisible: false,
      updateGoodsNumDialogVisible: false,
      addForm: {
        id: '',
        name: '测试测试',
        price: '404.00',
        number: '10',
        cat_id: '1',
        add_time: '',
      },
      editForm: {
        id: '',
        name: '',
        price: '',
        number: '',
        cat_id: '',
        update_time: '',
      },
      editNumForm: {
        id: '',
        name: '',
        prev_number: '',
        next_number: '',
        update_time: '',
        msg_user: ''
      },
      total: 0,
      now: 1,
      size: 8,
      expands: [],
      getRowKeys(row) {
        return row.id
      },
    }
  },
  methods: {
    getNowLocalTime() {
      let time = new Date().toLocaleString('chinese', {hour12: false}).split('/').join('-'); //转换成 1991-10-10 15:13:15 的格式
      return time;
    },
    getUsername() {
      let username = window.sessionStorage.getItem('username') ? window.sessionStorage.getItem('username') : '没有名字的家伙';
      return username;
    },
    /**
     * 展示商品信息
     *
     *
     * */
    async showAllGoods(currentPage, pageSize) {  //异步请求显示所有数据
      currentPage = currentPage ? currentPage : this.now;
      pageSize = pageSize ? pageSize : this.size;
      console.log(currentPage, pageSize)
      const {data: res} = await this.$http.get("goods/goodslist?currentPage=" + currentPage + "&pageSize=" + pageSize)
      console.log(res)
      if (res.data.length) {
        this.goodsTableData = res.data
        this.total = res.total
      } else {
        this.now = this.now - 1;
        await this.showAllGoods();
      }
    },
    /**
     * 展示分类信息
     * */
    // 展示分类
    async showAllCategory() {
      const {data: res} = await this.$http.get('goods/categorylist')
      if (res.code === '200') {
        this.categoryData = res.data;
      } else {
        this.$message.error(res.message)
      }
    },

    /**
     * 用来展示商品更新信息的
     * @param row
     * @param expandedRows
     * @returns {Promise<void>}
     */
    // row 获取当前行属性
    async showGoodsInfoById(row, expandedRows) {
      console.log(row);

    // 控制只展开一行。
      if (expandedRows.length) {
        this.expands = []
        if (row) {
          this.expands.push(row.id)
        }
      } else {
        this.expands = []
      }
      const {data: res} = await this.$http.post('goods/goodsInfoList', {
        id: row.id
      })
      console.log(res);
      if (res.code === '200') {
        this.goodsInfoTableData = res.data;
      } else {
        this.$message.error(res.message)
      }
    },


    async queryGoodsInfoByMonth(){
      // console.log(this.goodsInfoTableData[0].goods_id); // this.goodsInfoTableData[0].goods_id 商品id
      const {data : res } = await this.$http.post('goods/queryGoodsInfoByMonth',{
        MonthForm:this.queryGoodsInfoWithMonth,
        id:this.goodsInfoTableData[0].goods_id
      })
      console.log(res);
      if(res.code === '200'){
        this.goodsInfoTableData = res.data;
        this.queryGoodsInfoResult = res.result;
        this.$message.success(res.message)
      }else{
        this.$message.error(res.message)
      }
    },
    findPage(now_page) {//用来处理当前页的方法,page为当前页
      this.now = now_page;
      console.log('findpage', now_page, this.now)
      this.showAllGoods(now_page, this.size);
    },
    findSize(now_size) {//用来处理每页条数的方法,size为当前页条数
      this.size = now_size;
      console.log('findsize', now_size, this.size)
      this.showAllGoods(this.now, now_size);
    },
    clearAddInfo() {
      this.addForm = {};
    },
    clearEditInfo() {
      this.editForm = {};
    },
    clearEditGoodsNumInfo() {
      this.editNumForm = {};
    },
    addDialogClosed() {
      this.addForm = {};
      this.addDialogVisible = false;
    },
    updateDialogClosed() {
      this.updateDialogVisible = false;
    },
    updateGoodsNumDialogClosed() {
      this.updateGoodsNumDialogVisible = false;
    },


    async handleEdit(row) {
      this.updateDialogVisible = !this.updateDialogVisible //展示编辑表单
      const {data: res} = await this.$http.post('goods/findGoodsById', {
        id: row.id
      })
      // console.log(res);
      if (res.code === '200') {
        this.editForm = res.data[0]; // res.data 为嵌套对象，editform本身也是一个对象，需要直接拿到对象值
        console.log(this.editForm)
      } else {
        this.$message.error('查询错误！')
      }
    },
    async updateGoods() {
      let update_time = this.getNowLocalTime();
      this.editForm.update_time = update_time;
      const {data: res} = await this.$http.post('goods/updateGoods', {
        editGoodsForm: this.editForm
      })
      if (res.code === '200') {
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
      await this.showAllGoods();
      this.updateDialogVisible = false;
    },


    async addGoods() {
      // 获取当前时间
      let add_Date_Time = this.getNowLocalTime();
      this.addForm.add_time = add_Date_Time;
      console.log(this.addForm);
      const {data: res} = await this.$http.post('goods/addGoods', {
        goodsForm: this.addForm
      })
      if (res.code === '200') {
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
      await this.showAllGoods();
      this.addDialogVisible = false;
    },

    async handleNumEdit(row) {
      this.updateGoodsNumDialogVisible = !this.updateGoodsNumDialogVisible //展示编辑表单
      const {data: res} = await this.$http.post('goods/findGoodsById', {
        id: row.id
      })
      // console.log(res);
      let data = res.data[0];
      if (res.code === '200') {
        // this.editNumForm.id = res.data[0].id; // 一个个拿 没办法了 不想想了
        this.editNumForm.id = data.id;
        this.editNumForm.msg_user = this.getUsername();
        this.editNumForm.name = data.name;
        this.editNumForm.prev_number = data.number; //记录原本的数量
        this.editNumForm.next_number = data.number; //先展示原本的，修改的时候会直接修改里面的值，而上面原本的值不会变动。
        console.log(this.editNumForm)
      } else {
        this.$message.error(res.message)
      }
    },
    async updateGoodsNum() {
      this.editNumForm.update_time = this.getNowLocalTime();
      // 最新数据已经通过v-model修改了 所以这里不用赋值
      console.log(this.editNumForm);
      const {data: res} = await this.$http.post('goods/updateGoodsNumById', {
        updateNumForm: this.editNumForm
      })
      if (res.code === '200') {
        this.$message.success(res.message);
      } else {
        this.$message.error(res.message);
      }
      await this.showGoodsInfoById();
      this.updateGoodsNumDialogVisible = false;
    },
    async deleteGoodsById(row){
      const {data:res} = await this.$http.post('goods/deleteGoodsById',{
        id:row.id
      })
      if(res.code === '200') {
        this.$message.success(res.message)
      }else{
        this.$message.error(res.message)
      }
      await this.showAllGoods();
    },
  },
  created() {
    this.showAllGoods();
    this.showAllCategory();
  }
}
</script>

<style lang="less" scoped>

.el-col-12 {
  width: auto; //默认有50% 不会居中，需要让他自适应
}

.margin-left {
  margin-left: 20px;
}

// 设置一下  时间控件的宽度
.el-date-editor--monthrange.el-input, .el-date-editor--monthrange.el-input__inner {
  width: 400px;
}
</style>